package logic

import (
	"common/model"
	"context"

	"errors"
	"math/rand"
	product "product_server/proto"
	"time"
)

func (p *ProductServer) HelpBargain(ctx context.Context, req *product.HelpBargainRequest) (*product.HelpBargainResponse, error) {
	// 幂等性校验：同一用户只能帮砍一次
	existRecord, err := model.ExistRecord(req.OrderId, req.UserId)
	if err == nil {
		return &product.HelpBargainResponse{
			CutAmount:    existRecord.CutAmount,
			CurrentPrice: 0, // 可补查当前价
			CurrentCuts:  0, // 可补查当前次数
			Status:       0, // 可补查当前状态
			Message:      "该用户已帮砍过，不能重复帮砍",
		}, nil
	}
	// 查询砍价订单扩展表
	orderBargainInfo, err := model.GetOrderBargainInfo(req.OrderId)
	if err != nil {
		return nil, errors.New("砍价订单不存在")
	}
	// 检查活动状态
	activity, err := model.GteBargainActivity(orderBargainInfo.ActivityId, 0)
	if err != nil || activity == nil {
		return nil, errors.New("砍价活动不存在")
	}
	if orderBargainInfo.Status != 0 {
		return nil, errors.New("砍价已结束")
	}
	// 生成帮砍金额（可根据活动规则调整）
	cutAmount := rand.Float32()*(orderBargainInfo.CurrentPrice*0.1-0.01) + 0.01
	if cutAmount > orderBargainInfo.CurrentPrice {
		cutAmount = orderBargainInfo.CurrentPrice
	}
	newPrice := orderBargainInfo.CurrentPrice - cutAmount
	if newPrice < 0 {
		newPrice = 0
	}
	// 写入帮砍记录
	record := &model.BargainRecord{
		OrderId:    req.OrderId,
		ActivityId: orderBargainInfo.ActivityId,
		ProductId:  0, // 可补查
		UserId:     req.UserId,
		UserType:   1, // 帮砍者
		CutAmount:  cutAmount,
		CreatedAt:  time.Now(),
	}
	err = model.BargainRecordCreate(record)
	if err != nil {
		return nil, errors.New("帮砍记录创建失败")
	}

	// 更新砍价订单扩展表
	orderBargainInfo.CurrentPrice = newPrice
	orderBargainInfo.CurrentCuts += 1
	// 检查是否达到目标价格或砍价次数
	if orderBargainInfo.CurrentCuts >= activity.TotalCuts {
		orderBargainInfo.Status = 1 // 砍价成功
	}
	// 可根据业务判断是否砍价成功
	err = model.SaveOrderBargain(orderBargainInfo)
	if err != nil {
		return nil, errors.New("砍价订单更新失败")
	}

	return &product.HelpBargainResponse{
		CutAmount:    cutAmount,
		CurrentPrice: newPrice,
		CurrentCuts:  orderBargainInfo.CurrentCuts,
		Status:       orderBargainInfo.Status,
		Message:      "帮砍成功",
	}, nil
}
